#include "mainwindow.h"
#include <QFileDialog>
#include <QByteArray>
#include <QTextStream>
#include <QString>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    this->setGeometry(0, 0, 800, 480);
    mTextEdit = new QTextEdit();
    mFile = new QFile();
    mVBoxLayout = new QVBoxLayout();
    mVWidget = new QWidget();
    mHBoxLayout = new QHBoxLayout();
    mHWidget = new QWidget();
    mOpenButton = new QPushButton();
    mCloseButton = new QPushButton();

    mOpenButton->setMaximumWidth(120);
    mOpenButton->setMinimumHeight(50);
    mOpenButton->setText("打开");

    mCloseButton->setMaximumWidth(120);
    mCloseButton->setMinimumHeight(50);
    mCloseButton->setText("关闭");
    mCloseButton->setEnabled(false);

    mHBoxLayout->addWidget(mOpenButton);
    mHBoxLayout->addWidget(mCloseButton);
    mHWidget->setLayout(mHBoxLayout);

    mVBoxLayout->addWidget(mTextEdit);
    mVBoxLayout->addWidget(mHWidget);
    mVWidget->setLayout(mVBoxLayout);

    setCentralWidget(mVWidget);

    connect(mOpenButton, &QPushButton::clicked,
            this, &MainWindow::openFile);
    connect(mCloseButton, &QPushButton::clicked,
            this, &MainWindow::closeFile);
}

MainWindow::~MainWindow()
{

}

bool MainWindow::openFile()
{
    /* 获取文件路径 */
    QString filePath = QFileDialog::getOpenFileName(this);
    mFile->setFileName(filePath);
    if (!mFile->exists()) {
        return false;
    }

    if (!mFile->open(QIODevice::ReadOnly | QIODevice::Text)) {
        return false;
    }

    QTextStream stream(mFile);

    mTextEdit->setPlainText(stream.readAll());
    mOpenButton->setEnabled(false);
    mCloseButton->setEnabled(true);
    mFile->close();
    return true;
}

bool MainWindow::closeFile()
{
    if (!mOpenButton->isEnabled()) {
        QString text = mTextEdit->toPlainText();

        if (!mFile->open(QIODevice::ReadWrite | QIODevice::Text)) {
            return false;
        }

        QString str = mTextEdit->toPlainText();
        QTextStream stream(mFile);
        stream << str;

//        QByteArray textBytes = text.toUtf8();
//        mFile->write(textBytes, textBytes.length());
        mTextEdit->clear();
        mOpenButton->setEnabled(true);
        mCloseButton->setEnabled(false);
        mFile->close();
    } else {
        qDebug() << "-----------" << endl;
    }
    return true;
}
